using System;
using System.Data;
using PropertyExpression.Common;

namespace PropertyExpression.ReactiveRelation.Test
{
    internal class ContextProvider
    {
        private readonly CalcStorage<DataClassesDataContext> calcStorage;

        public ContextProvider(Action<ICalcRegistrator<DataClassesDataContext>> initAction)
        {
            calcStorage = new CalcStorage<DataClassesDataContext>(initAction);
        }

        public void Execute(Action<DataClassesDataContext, ICalcExecutor> action, 
            IsolationLevel isolationLevel)
        {
            Execute(action.ToFunc(), isolationLevel);
        }

        public TResult Execute<TResult>(
            Func<DataClassesDataContext, ICalcExecutor, TResult> func, IsolationLevel isolationLevel)
        {
            return DataContextProviderHolder.Provider
                .Execute(dataContext =>
                         func(
                             dataContext,
                             CalcStorageExtensions.CreateCalcExecutor(
                                 () => calcStorage,
                                 () => dataContext
                                 )
                             ),
                         isolationLevel);
        }
    }
}